import GoodsDiv from '@/components/GoodsDiv';
import RightFixed from '@/layouts/RightFixed';
import TopBread from '@/layouts/TopBread';
import { allGoods, selectByName } from '@/services/commodity';
import { colorStr } from '@/utils/utils';
import { Button, Input, Menu, message } from 'antd';
import { useCallback, useEffect, useState } from 'react';
import { history } from 'umi';
import { optionEat, optionsUse } from '../BackPages/Sale/CreateGoods/constants';
import styles from './index.less';

const GoodsPage: React.FC = () => {
  const { Search } = Input;
  const { lastRoute, titleValue, listByName }: any = history?.location?.query;
  const [search, setSearch] = useState<string>(titleValue !== '' ? titleValue : '');
  const [color, setColor] = useState<string>(localStorage.getItem('color') || '#1a7721');
  const [menuKey, setMenuKey] = useState('1');
  const [list, setList] = useState<any[]>([]);
  const [selectList, setSelectList] = useState<any[]>([]);
  const [type, setType] = useState<string>('食用保健');
  const [pageSize, setPageSize] = useState(10);
  const [typeEatOneCurr, setTypeEatOneCurr] = useState<string>('');
  const [typeEatTwoCurr, setTypeEatTwoCurr] = useState<string>('');
  const [typeEatThreeCurr, setTypeEatThreeCurr] = useState<string>('');
  const [typeUseOneCurr, setTypeUseOneCurr] = useState<string>('');
  const [typeUseTwoCurr, setTypeUseTwoCurr] = useState<string>('');
  const [pageSizeSelect, setPageSizeSelect] = useState(10);

  const getList = useCallback(async () => {
    setSearch('');
    setSelectList([]);
    try {
      await allGoods({
        type: type,
        pageIndex: 1,
        pageSize: type === '食用保健' ? pageSize : 100,
        typeUseOne: typeUseOneCurr,
        typeUseTwo: typeUseTwoCurr,
        typeEatOne: typeEatOneCurr,
        typeEatTwo: typeEatTwoCurr,
        typeEatThree: typeEatThreeCurr,
      }).then((res) => {
        setList(res.list);
      });
    } catch (error) {
      console.log(error);
    }
  }, [
    pageSize,
    type,
    typeEatOneCurr,
    typeEatThreeCurr,
    typeEatTwoCurr,
    typeUseOneCurr,
    typeUseTwoCurr,
  ]);

  const selectGoodsByName = useCallback(
    async (value: any) => {
      try {
        await selectByName({
          type: type,
          title: value,
          pageSize: pageSizeSelect,
          pageIndex: 1,
        }).then((res) => {
          setSelectList(res.list);
          if (res.list.length === 0) {
            message.loading('您搜索的商品不存在，正在为您加载全部商品···');
            setSearch('');
            setTimeout(() => {
              getList();
            }, 1000);
          }
        });
      } catch (error) {
        console.log(error);
      }
    },
    [getList, pageSizeSelect, type],
  );

  const onSearch = (value: string) => {
    setType('食用保健');
    setMenuKey('1');
    selectGoodsByName(value);
  };

  useEffect(() => {
    if (listByName === undefined) {
      getList();
    }
  }, [getList, listByName]);

  useEffect(() => {
    if (listByName !== undefined) {
      selectGoodsByName(titleValue);
    }
  }, [selectGoodsByName, listByName, titleValue]);

  const selectGoodsByNameChange = useCallback(
    async (typeCurr: any) => {
      try {
        await selectByName({
          type: typeCurr,
          title: '',
          pageSize: pageSizeSelect,
          pageIndex: 1,
        }).then((res) => {
          setSelectList(res.list);
          if (res.list.length === 0) {
            message.loading('您搜索的商品不存在，正在为您加载全部商品···');
            setTimeout(() => {
              getList();
            }, 1000);
          }
        });
      } catch (error) {
        console.log(error);
      }
    },
    [getList, pageSizeSelect],
  );

  // 切换订单状态展示元素
  const menuChange = (e: any) => {
    setMenuKey(e.key);
    if (e.key === '1') {
      selectGoodsByNameChange('食用保健');
      setTypeUseOneCurr('');
      setTypeUseTwoCurr('');
      setType('食用保健');
      setSearch('');
    } else {
      selectGoodsByNameChange('器械保健');
      setTypeEatOneCurr('');
      setTypeEatTwoCurr('');
      setTypeEatThreeCurr('');
      setType('器械保健');
      setSearch('');
    }
  };

  return (
    <div className={styles.container}>
      <TopBread lastRoute={lastRoute} now={'商品浏览'} setColorParent={setColor} />
      <div className={styles.content}>
        <div className={styles.menuBorder}>
          <Menu
            mode="horizontal"
            className={styles.menuStyle}
            onClick={menuChange}
            defaultSelectedKeys={[menuKey]}
            style={{
              background: colorStr(6),
              border: 0,
              height: 58,
              fontSize: 18,
              padding: '4px 41px',
            }}
          >
            <Menu.Item key={'1'}>食用保健</Menu.Item>
            <Menu.Item key={'2'}>器械保健</Menu.Item>
          </Menu>
        </div>
        <div className={styles.searchList}>
          <Search
            placeholder={`请输入想要购买的商品`}
            onSearch={onSearch}
            onChange={(e) => {
              setSearch(e.target.value);
            }}
            value={search}
            style={{
              width: 391,
              border: `1px solid ${colorStr(6)}`,
              borderRadius: 6,
              color: `${colorStr(9)}`,
            }}
          />
          <div
            style={{ color: '#fff', marginLeft: 20, cursor: 'pointer' }}
            onClick={() => {
              setSearch('');
              getList();
              setSelectList([]);
            }}
          >
            清空搜索
          </div>
        </div>
        <div className={styles.information}>
          {menuKey === '1' ? (
            <div className={styles.chooseBox}>
              <div style={{ marginBottom: 25, fontSize: 18, fontWeight: 600 }}>分类</div>
              {optionEat.map((items) => (
                <div title={`${items.label}`} className={styles.type} key={items.value}>
                  <div className={styles.typeTitle}>{items.label}：</div>
                  <div className={styles.spanLazy}>
                    {items.children.map((item) => (
                      <div
                        key={item.value}
                        className={
                          item.label !== '免疫力低下者' && item.label !== '儿童/青少年'
                            ? styles.spanDiv
                            : styles.spanLong
                        }
                      >
                        {typeEatOneCurr === item.value ||
                        typeEatTwoCurr === item.value ||
                        typeEatThreeCurr === item.value ? (
                          <span
                            className={styles.selectedSpan}
                            onClick={() => {
                              switch (item.value.charAt(2)) {
                                case '1':
                                  setTypeEatOneCurr('');
                                  break;
                                case '2':
                                  setTypeEatTwoCurr('');
                                  break;
                                case '3':
                                  setTypeEatThreeCurr('');
                                  break;
                                default:
                                  break;
                              }
                            }}
                          >
                            {item.label}
                          </span>
                        ) : (
                          <span
                            className={styles.notSelectSpan}
                            onClick={() => {
                              switch (item.value.charAt(2)) {
                                case '1':
                                  setTypeEatOneCurr(item.value);
                                  break;
                                case '2':
                                  setTypeEatTwoCurr(item.value);
                                  break;
                                case '3':
                                  setTypeEatThreeCurr(item.value);
                                  break;
                                default:
                                  break;
                              }
                            }}
                          >
                            {item.label}
                          </span>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className={styles.chooseBox}>
              <div style={{ marginBottom: 25, fontSize: 18, fontWeight: 600 }}>分类</div>
              {optionsUse.map((items) => (
                <div title={`${items.label}`} className={styles.type} key={items.value}>
                  <div className={styles.typeTitle}>{items.label}：</div>
                  <div className={styles.spanLazy}>
                    {items.children.map((item) => (
                      <div key={item.value} className={styles.spanDiv}>
                        <span
                          className={
                            typeUseOneCurr === item.value || typeUseTwoCurr === item.value
                              ? styles.selectedSpan
                              : styles.notSelectSpan
                          }
                          onClick={() => {
                            switch (item.value.charAt(2)) {
                              case '1':
                                setTypeUseOneCurr(item.value);
                                break;
                              case '2':
                                setTypeUseTwoCurr(item.value);
                                break;
                              default:
                                break;
                            }
                          }}
                        >
                          {item.label}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
        <div className={styles.goodsContent} style={{ minHeight: menuKey === '1' ? 559 : 605 }}>
          <GoodsDiv
            goods={selectList.length !== 0 ? selectList : list === null ? [] : list}
            ifHomePage={'2'}
          />
          <div className={styles.bottomLoading}>
            {(selectList.length !== 0 ? selectList.length < pageSize : list.length < pageSize) ? (
              <span>暂无更多商品</span>
            ) : (
              type !== '器械保健' && (
                <Button
                  onClick={() => {
                    selectList.length !== 0
                      ? setPageSizeSelect(pageSizeSelect + 5)
                      : setPageSize(pageSize + 5);
                  }}
                  style={{ background: colorStr(4), color: '#fff', height: 50 }}
                >
                  查看更多商品
                </Button>
              )
            )}
          </div>
        </div>
        <RightFixed color={color} thisRoute={'商品浏览'} />
      </div>
    </div>
  );
};

export default GoodsPage;
